<template>
  <div class="virtual-container" ref="container">
    <div :style="heightStyle" class="virtual-container__layout"></div>
    <div class="virtual-container__show" :style="transformStyle">
      <div
        class="virtual-container__show--item"
        v-for="(item, index) in listCore"
        :key="item.id"
      >
        <span>{{ item.id }}</span> - <span>{{ item.name }}</span> -
        <span>{{ item.words }}</span>
      </div>
    </div>
  </div>
</template>

<script>
const bufferSize = 5;
const all = 1000;
// const all = 200000;
import * as utils from "@/utils/index.js";

export default {
  name: "virtual-list",
  data() {
    return {
      scrollTop: 0,
      visibleCount: 10,
      start: 0,
      dataState: utils.listCreate(all),
    };
  },
  computed: {
    heightStyle() {
      const nums = this.dataState.length;
      return {
        height: `${nums * 40}px`,
        width: "520px",
      };
    },
    listCore() {
      const start = Math.max(this.start - bufferSize, 0);
      const finish = Math.min(this.start + this.visibleCount + bufferSize, all);
      // const start = this.start;
      // const finish = this.start + this.visibleCount;
      // console.log(this.start, start, finish, finish - start);
      return this.dataState.slice(start, finish);
    },
    transformStyle() {
      return {
        transform: `translateY(${this.scrollTop}px)`,
      };
    },
  },
  mounted() {
    this.onScroll();
    this.getIndexState();
  },
  methods: {
    onScroll() {
      const container = this.$refs.container;
      container.addEventListener("scroll", (e) => {
        this.scrollTop = e.target.scrollTop;
        this.start = ~~(this.scrollTop / 40);
        console.log("this.start", this.start, this.scrollTop);
      });
    },
    getIndexState() {
      const len = this.dataState.length;
      console.log("length", len);
      console.log(this.dataState);
      console.log(this.dataState[len - 1].email);
    },
  },
};
</script>

<style lang="scss" scoped>
.virtual-container {
  overflow-y: scroll;
  height: 400px;
  position: relative;
  border: 3px solid red;

  &__show {
    position: absolute;
    top: 0;
    z-index: 90;
    bottom: 0;
    width: 100%;

    &--item {
      line-height: 40px;
      // height: 80px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
